/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#if 0
#include "maya_local.h"

#include "../etc/rapidxml/rapidxml_ext.hpp"
#include "../etc/rapidxml/rapidxml_print.hpp"
using namespace rapidxml;

const char *ProjectVersion(void);


/*-----------------------------------------------------------------------------
	Level export stuff :
-----------------------------------------------------------------------------*/

//
//	EMLevelTranslator::WalkDAG
//
EMLevelTranslator::EMLevelTranslator()
{
	
}


//
//	EMLevelTranslator::WalkDAG
//
EMLevelTranslator::~EMLevelTranslator()
{
}


//
//	EMLevelTranslator::WalkDAG
//
MStatus EMLevelTranslator::writer(const MFileObject &file, const MString &optionsString, MPxFileTranslator::FileAccessMode mode)
{
	IDisposingProxy<ELevelAssembler>	level = new ELevelAssembler();

	string	path = file.fullName().asChar();
	LOG_SPLIT(va("Level export : %s", path.c_str()));
	
		//
		//	Parse hierarchy :
		//
		//	get root path :
		MItDag		dag_iter(MItDag::kDepthFirst, MFn::kTransform);
		MFnDagNode	root_node( dag_iter.root() );
		MDagPath	dag_path;
		MAYA_CALL( root_node.getPath( dag_path ) );

		LOGF("Parsing : DAG hierarchy\r\n");
		MAYA_CALL( ParseHierarchy( level->GetRoot(), dag_path, 0 ) );		

	
		
		//		
		//	Parse animation curves :
		//
		LOGF("Parsing : Animation\r\n");
		MAYA_CALL( ParseAnimCurves() );

		//
		//	Preprocess level and write XML :
		//
		level->Process();
		level->WriteXML(path.c_str());


	LOG_SPLIT("");

	return MStatus::kSuccess;
}



EMatrix4	Matrix4ExtractScaleMatrix( const EMatrix4 &M ) 
{
	//EMatrix4 M2 = Matrix4Inverse( M );
	EVec3	x_axis	=	EVec3( M(0,0), M(1,0), M(2,0) );
	EVec3	y_axis	=	EVec3( M(0,1), M(1,1), M(2,1) );
	EVec3	z_axis	=	EVec3( M(0,2), M(1,2), M(2,2) );
	float	sx		=	Vec3Length( x_axis );
	float	sy		=	Vec3Length( y_axis );
	float	sz		=	Vec3Length( z_axis );
	
	return Matrix4Scale( sx, sy, sz );
}


//
//	EMLevelTranslator::ParseHierarchy
//
MStatus EMLevelTranslator::ParseHierarchy( IPxLvNode lv_node, MDagPath node_path, uint depth )
{
	MStatus status;
	
	MObject	node = node_path.node();

	//
	//	Setup transformation for current node :
	//	NOTE : root node does not have transform
	//	
	if (depth!=0) {
		//	check transform node :	
		if (!node.hasFn(MFn::kTransform)) {
			LOG_ERROR(va("DAG node '%s' is not transform node", node_path.fullPathName().asChar()));
			return MS::kFailure;
		}

		//	set entity name :		
		lv_node->entity_desc.SetValue("dagpath", node_path.fullPathName().asChar());

		//	set entity transform :		
		MFnTransform	transform(node);

		//MPlug	tx		(node,	MPxTransform::translateX	);
		//MPlug	ty		(node,	MPxTransform::translateY	);
		//MPlug	tz		(node,	MPxTransform::translateZ	);
		//MPlug	rx		(node,	MPxTransform::rotateX		);
		//MPlug	ry		(node,	MPxTransform::rotateY		);
		//MPlug	rz		(node,	MPxTransform::rotateZ		);
		//MPlug	sx		(node,	MPxTransform::scaleX		);
		//MPlug	sy		(node,	MPxTransform::scaleY		);
		//MPlug	sz		(node,	MPxTransform::scaleZ		);
		//MPlug	vis		(node,	MPxTransform::visibility	);
		//MPlug	order	(node,	MPxTransform::rotateOrder	);

		////	BUG? : getting value of built-in transforms causes stange behavior :
		//lv_node->xform->SetTranslation	( EVec3(tx.asFloat(), ty.asFloat(), tz.asFloat()) );		
		//lv_node->xform->SetRotation		( EVec3(rx.asFloat(), ry.asFloat(), rz.asFloat()) );		
		//lv_node->xform->SetScale		( EVec3(sx.asFloat(), sy.asFloat(), sz.asFloat()) );		
		//lv_node->xform->SetVisibility	( vis.asBool() );
		//lv_node->xform->SetRotateOrder	( (ERotateOrder_t)order.asInt() );	// hope, this will work...
		EMatrix4	T =		MMatrix2EMatrix4( transform.transformation().asMatrix());
		
		lv_node->scale	=	Matrix4ExtractScaleMatrix( T );
		T = T * Matrix4Inverse( lv_node->scale );
		
		lv_node->entity_desc.SetValue("transform", va("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g",
			T(0,0), T(0,1), T(0,2), T(0,3), 
			T(1,0), T(1,1), T(1,2), T(1,3), 
			T(2,0), T(2,1), T(2,2), T(2,3), 
			T(3,0), T(3,1), T(3,2), T(3,3)
			));
				
	} 
	
	//
	//	Iterate over all child :	
	//
	for (uint i=0; i<node_path.childCount(); i++) 
	{
		MObject		child		=	node_path.child(i);
		MDagPath	child_path	=	node_path;
		child_path.push( child );	// extend path to child

		//	skip these objects :
		if (child_path.fullPathName()=="|groundPlane_transform"	)	continue;
		if (child_path.fullPathName()=="|Manipulator1"			)	continue;
		if (child_path.fullPathName()=="|UniversalManip"		)	continue;
		if (child_path.fullPathName()=="|CubeCompass"			)	continue;
		if (child_path.fullPathName()=="|persp"					)	continue;
		if (child_path.fullPathName()=="|top"					)	continue;
		if (child_path.fullPathName()=="|front"					)	continue;
		if (child_path.fullPathName()=="|side"					)	continue;

		//		
		//	Child is a locator, add entity desc :
		//
		if (child.hasFn(MFn::kLocator)) {
			MAYA_CALL( ParseLocatorNode( lv_node, child ) );
			continue;
		}

		//		
		//	Child is a mesh :
		//
		if (child.hasFn(MFn::kMesh)) {
			MFnDagNode dag_mesh(child);
			//	skip intermediate meshes, such as bool operands and etc.
			if (dag_mesh.isIntermediateObject()) {
				continue;
			}
			MAYA_CALL( ParseMeshNode( lv_node, child, child_path ) );
			continue;
		}


		//
		//	Child is a tranform node, 
		//	continue recursive descending :
		//
		if (child.hasFn(MFn::kTransform)) 
		{
			IPxLvNode	lv_child_node = new ELvNode();
			lv_node->AddNode(lv_child_node);
		
			MAYA_CALL( ParseHierarchy(lv_child_node, child_path, depth+1) );
			continue;
		}
	}
	
	return MS::kSuccess;
}


/*-----------------------------------------------------------------------------
	Node parsers :
-----------------------------------------------------------------------------*/

//
//	EMLevelTranslator::ParseAnimCurves
//
MStatus EMLevelTranslator::ParseAnimCurves( void )
{
	MStatus	status;

	MItDependencyNodes	dni(MFn::kAnimCurve, &status);
	MAYA_CALL(status);
	
	uint n = 0;

	//	iterate over all curves in DG :	
	for (dni.reset(); !dni.isDone(); dni.next()) {
		MObject	curve	=	dni.thisNode();
	
		//	BUG? : filter the curves out :
		if (!curve.hasFn(MFn::kAnimCurve)) {
			continue;
		}

		//	get dependency node for current curve :
		MFnDependencyNode	node_curve(curve, &status);
		MAYA_CALL(status);
		

		//	get 'output' attribute : 
		MObject curve_out_attr = node_curve.attribute(MString("output"), &status);
		MAYA_CALL(status);
		
		MPlug	curve_out(curve, curve_out_attr);
		
		//	search for all connected attributes,
		MPlugArray	conn_to;
		if (!curve_out.connectedTo(conn_to, false, true, &status)) {
			continue;	// this curve has no connections
		}

		LOGF("Anim curve : %s\r\n", node_curve.name().asChar());
				
		for (uint i=0; i<conn_to.length(); i++) {
			MPlug conn = conn_to[i];
			
			LOGF("  %s\r\n", conn.name().asChar());
		}

		n++;
		
	}
	
	LOGF("%d anim curves have been found\r\n", n);
	
	return MS::kSuccess;
}

/*-----------------------------------------------------------------------------
	Locator :
-----------------------------------------------------------------------------*/

//
//	EMLevelTranslator::ParseLocatorNode
//
MStatus EMLevelTranslator::ParseLocatorNode( IPxLvNode lv_node, MObject &obj )
{
	MStatus status;

	MFnDependencyNode	dnode(obj);		//	get dependency node from current MObject
	MFnTypedAttribute		fn_typed;
	MFnNumericAttribute		fn_numeric;
	MFnCompoundAttribute	fn_compound;
	
	//	NOTE : Look "cgfxAttrDef.cpp" to get how to parse node's atributes.
			
	for (uint i=0; i<dnode.attributeCount(); i++) {

		MObject attr = dnode.attribute(i);
		MPlug	attr_plug(obj, attr);

		//	remove object name: "object.attribute" -> "attribute" :
		MString attr_name	=	attr_plug.name();
		MString key			=	attr_name.substring( attr_name.index('.')+1, attr_name.length());
		//LOGF("[%s]\r\n", skey.asChar());

		//	Compound attribute (color or vector) :
		//if ( fn_compound.setObject(attr) ) 
		//{
		//	MString key	=	attr_plug.name();
		//	EVec4	vec4(0,0,0,0);
		//	uint  num = fn_compound.numChildren();
		//	num = Clamp<uint>(num, 0, 4);
		//	
		//	for (uint j=0; j<num; j++) {
		//		vec4.v[j] = attr_plug.child(j).asFloat();
		//	}

		//	lv_node_ent->SetValue( key.asChar(), va("%g  %g  %g  %g ", vec4.x, vec4.y, vec4.z, vec4.w) );
		//} 
		//else
		//
		////	Numberic attribute :
		//if ( fn_numeric.setObject(attr) ) 
		//{
		//	MString key	=	attr_plug.name();
		//	float fval	=	attr_plug.asFloat();
		//	
		//	lv_node_ent->SetValue( key.asChar(), va("%g ", fval) );
		//} 
		//else
		
		//	'elv_bbox' - is a vector value 
		//	and it will not be parsed as string attribute :
		if (key=="elv_bbox") {
			EVec4	bbox = Maya_ReadVector(obj, attr, EVec4(0,0,0,1));
			lv_node->entity_desc.SetValue( "bbox", va("%g  %g  %g ", bbox.x, bbox.y, bbox.z));
		} else

		//		
		//	String attribute :
		if ( fn_typed.setObject(attr) && fn_typed.attrType() == MFnData::kString) 
		{
			MString	value	=	"";
			attr_plug.getValue(value);
			
			if (key.substring(0,3)=="elv_") {
				key = key.substring(4, key.length()-1);
				lv_node->entity_desc.SetValue( key.asChar(), value.asChar() );
			}
		} 
		else {	
			// unrecognizable attribute type
		}
	}
	

	return MStatus::kSuccess;
}


/*-----------------------------------------------------------------------------
	Mesh :
-----------------------------------------------------------------------------*/

MStatus GetLocalVertexIndex(MIntArray poly_vert_inds, int global_vert_index, int &local_vert_index) {
	for (uint i=0; i<poly_vert_inds.length(); i++) {
		if (poly_vert_inds[i]==global_vert_index) {
			local_vert_index = i;
			return MS::kSuccess;
		}
	}
	return MS::kFailure;
}

//
//	EMLevelTranslator::ParseMeshNode
//
MStatus EMLevelTranslator::ParseMeshNode( IPxLvNode lv_node, MObject &obj, MDagPath &path )
{
	LOGF("\r\nParsing mesh : %s\r\n", path.fullPathName().asChar());

	MStatus	status;

	MFnMesh				mesh(obj);
	MString				uv_set_name;
	MString				clr_set_name;
	bool				has_color;
	MPointArray			vertex_array;
	MColorArray			color_array;
	MFloatVectorArray	normal_array;
	MFloatVectorArray	tangent_array;
	MFloatVectorArray	binormal_array;
	MFloatArray			u_array;
	MFloatArray			v_array;

	IPxTriMesh		lv_mesh	=	ge->CreateTriMesh( LEVEL_MESH_FORMAT );
	lv_node->rendmesh	=	lv_mesh;

	//
	//	Get Color and UV set names :
	//
	MAYA_CALL( mesh.getCurrentUVSetName(uv_set_name) );
	MAYA_CALL( mesh.getCurrentColorSetName(clr_set_name) );

	//	NOTE : UV set is always presented, but color is not.
	if (clr_set_name!="") {
		MAYA_CALL( mesh.getFaceVertexColors(color_array, &clr_set_name, &MColor(1.0f, 1.0f, 1.0f, 1.0f) ) );
		has_color = true;
	} else {
		has_color = false;
	}
	
	//
	//	Get positions, normals, tangents, etc :
	//
	MAYA_CALL( mesh.getPoints( vertex_array, MSpace::kObject ) );
	MAYA_CALL( mesh.getNormals( normal_array, MSpace::kObject ) );
	MAYA_CALL( mesh.getTangents( tangent_array, MSpace::kObject, &uv_set_name ) );
	MAYA_CALL( mesh.getBinormals( binormal_array, MSpace::kObject, &uv_set_name ) );
	MAYA_CALL( mesh.getUVs(u_array, v_array, &uv_set_name) );
	
	//
	//	Get number of instanced copy :
	//
	MAYA_CALL( path.extendToShape() );
	
	int instance_num = 0;
	if (path.isInstanced()) {
		instance_num = path.instanceNumber();
	}

	//
	//	Get connected shaders :	
	//
	MObjectArray	shaders;
	MIntArray		face_shader_inds;
	MAYA_CALL( mesh.getConnectedShaders(instance_num, shaders, face_shader_inds) );
	LOGF("   Mesh has %d faces and %d shaders\r\n", face_shader_inds.length(), shaders.length());
		//for (uint i=0; i<face_shader_inds.length(); i++) {
		//	LOGF(" %d ", face_shader_inds[i]);
		//}
		//LOGF("\r\n");
	
	MStringArray	texture_names;
	texture_names.setLength( shaders.length() );
	
	for (uint i=0; i<shaders.length(); i++) {
		MAYA_CALL( ParseConnectedShader(shaders[i], texture_names[i]) );
		LOGF("   Texture : %s\r\n", texture_names[i].asChar());
	}
	
	//
	//	Get faces :
	//
	MItMeshPolygon	poly_iter(obj, &status);
	MAYA_CALL(status);
	//	For each face :
	for ( poly_iter.reset();  !poly_iter.isDone();  poly_iter.next()) {

		uint face_id = poly_iter.index();
				
		int num_tris = 0;
		MAYA_CALL( poly_iter.numTriangles(num_tris) );
		
		MPointArray	points;
		MIntArray	tri_vertex_list;
		MIntArray	poly_vertex_list;

		MAYA_CALL( poly_iter.getVertices( poly_vertex_list ) );
		
		//	Attach shading group :
		EShadingGroup	sg;
		sg.start	=	lv_mesh->GetTriangleNum();
		sg.num		=	num_tris;
		sg.shader	=	texture_names[ face_shader_inds[ face_id ] ].asChar();
		lv_mesh->AttachSG( sg );

		//	For each triangle in face :		
		for (uint j=0; j<(uint)num_tris; j++) {
			
			MAYA_CALL( poly_iter.getTriangle(j, points, tri_vertex_list) );
			
			uint tri_inds[3];

			//	For each triangle vertex :			
			for (uint k=0; k<3; k++) {
				EVertex	vertex;
				MVector	n;
				MColor	c(1,0,0,1);
				float u=0, v=0;
				int local_index;
				
				MAYA_CALL( GetLocalVertexIndex(poly_vertex_list, tri_vertex_list[k], local_index) );
				
				vertex.position.x	=	points[k].x / points[k].w;
				vertex.position.y	=	points[k].y / points[k].w;
				vertex.position.z	=	points[k].z / points[k].w;
				
				MAYA_CALL( mesh.getFaceVertexNormal(face_id, tri_vertex_list[k], n) );
				MAYA_CALL( mesh.getPolygonUV(face_id, local_index, u, v, &uv_set_name) );
				
				if (has_color) {				
					MAYA_CALL( poly_iter.getColor(c, local_index) );
				}

				vertex.normal		=	EVec3(n.x, n.y, n.z);
				vertex.uv0			=	EVec2( u, v );
				vertex.color0		=	EVec4(c.r, c.g, c.b, c.a);
				
				tri_inds[k] = lv_mesh->AddVertex( vertex );
			}
			
			lv_mesh->AddTriangle(tri_inds[0], tri_inds[1], tri_inds[2]);
		}
	}

	lv_mesh->MergeVertices();	
	lv_mesh->GlueSGs();	
	
	lv_mesh->Transform( lv_node->scale );
	lv_node->scale = Matrix4Identity();
	
	
	LOGF("\r\n");
	return MStatus::kSuccess;
}


//
//	EMLevelTranslator::ParseConnectedShader
//	TODO : if no shader connected, make virtual texture like "*colorFF8040FF"
//
MStatus EMLevelTranslator::ParseConnectedShader(MObject &set, MString &texture_name)
{
	MStatus	status;

	MObject shader_node = FindShader(set);
	if (MObject::kNullObj == shader_node) {
		return MS::kSuccess;	//	just no shader, so it is not an error.
	}


	MPlug color_plug = MFnDependencyNode(shader_node).findPlug("color", &status);
	MAYA_CALL(status);
	
	
	MItDependencyGraph itDG(color_plug, MFn::kFileTexture,
							MItDependencyGraph::kUpstream, 
							MItDependencyGraph::kBreadthFirst,
							MItDependencyGraph::kNodeLevel, 
							&status);
	MAYA_CALL(status);

	//	disable automatic pruning so that we can locate a specific plug 
	itDG.disablePruningOnFilter();

	//	If no texture file it means, 
	//	that no textures are connected to color,
	//	so set texture name to virtual texture name.
	if (itDG.isDone()) {
	
		if (color_plug.isCompound()) {
			float fr,fg,fb;
			ASSERT(color_plug.numChildren()==3);
			color_plug.child(0).getValue(fr);
			color_plug.child(1).getValue(fg);
			color_plug.child(2).getValue(fb);
			unsigned char r = fr*255;
			unsigned char g = fg*255;
			unsigned char b = fb*255;
			texture_name = va("*color%02X%02X%02XFF", r, g, b);
		}
	
	} else {
		MObject textureNode = itDG.thisNode();
		MString fullpath;
		MString projdir = Maya_ProjectDir();
		
		MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName");
		filenamePlug.getValue(fullpath);
		
		//	strip out full path :
		texture_name = fullpath.substring( projdir.length()+1, fullpath.length() );
	}	
	
	return MS::kSuccess;	
}


//
//	EMLevelTranslator::FindShader
//
//	Summary	:	finds the shading node for the given shading group set node
//	Args    :	setNode - the shading group set node
//	Returns :	the shader node for setNode if found;
//				MObject::kNullObj otherwise
//
MObject EMLevelTranslator::FindShader(const MObject& set) 
{

	MFnDependencyNode fn_node(set);
	MPlug shader_plug = fn_node.findPlug("surfaceShader");
			
	if (!shader_plug.isNull()) 
	{			
		//	buffer for all plug, 
		//	that are connected as destination of current set node :
		MPlugArray connected_plugs;	

		//	get all the plugs that are connected as the destination of this 
		//	surfaceShader plug so we can find the surface shaderNode
		MStatus status;
		shader_plug.connectedTo(connected_plugs, true, false, &status);
		
		if (MStatus::kFailure == status) {
			MGlobal::displayError("MPlug::connectedTo");
			return MObject::kNullObj;
		}

		if (1 != connected_plugs.length()) {
			MGlobal::displayError("Error getting shader");
		} else {
			return connected_plugs[0].node();
		}
	}
	
	return MObject::kNullObj;
}

#endif


















